<?php
namespace haibao\cms\data;


class PageControl extends \haibao\cms\data\BaseMysql{
    
	public function __construct($modelName = null){
		if (!$modelName){
			$modelName = '\haibao\cms\model\data\PageControl'; 
		}
		parent::__construct($modelName);
	}
	
	public function deleteDataById($id,$type){
		
		if($type == 'update'){
			$sql = 'update PageControlData set Status='.\haibao\cms\model\data\PageControlData::STATUS_DELETE.' where Id=%s';
			$this->query($sql,array($id));
		}elseif($type == 'delete'){
			$sql = 'delete from PageControlData where Id=%s';
			$this->query($sql,array($id));
			$sql = 'delete from PageControlDataPeriod where ControlDataId=%s';
			$this->query($sql,array($id));
		}
	}
	
	public function updatePageControlData($dataModel,$createBy,$createTime){
		$this->beginTranscation();
		
		try{
			$arrSet = array(
					\haibao\cms\model\filter\PageControlData::CONDITION_FIELD_NAME_PARAMETER_VALUE=>$dataModel->ParameterValue,
					\haibao\cms\model\filter\PageControlData::CONDITION_FIELD_NAME_DESCRIPTION=>$dataModel->Description,
					\haibao\cms\model\filter\PageControlData::CONDITION_FIELD_NAME_ORDER_NO=>$dataModel->OrderNo,
					\haibao\cms\model\filter\PageControlData::CONDITION_FIELD_NAME_CREATE_BY=>$dataModel->CreateBy
			);
			$this->setModelName('\haibao\cms\model\data\PageControlData');
			$this->updateById($dataModel->Id, $arrSet);
			
			//更新排期
			$newPeriods = array();
			$updatePeriods = array();
			$deletePeriods = array();
			$oldPeriods = $this->getPeriodsByDataId($dataModel->Id);
			$oldPeriodIds = array();
			foreach ($oldPeriods as $oldPeriod){
				array_push($oldPeriodIds,$oldPeriod->Id);
			}
			$periods = $dataModel->Periods;
			foreach ($periods as $period){
				if (!$period->Id){
					$period->CreateTime = $createTime;
					$period->CreateBy = $createBy;
					$period->Status = \haibao\cms\model\data\PageControlDataPeriod::STATUS_ENABLE;
					array_push($newPeriods,$period);
				}
				else if ($period->Id){
					if (in_array($period->Id,$oldPeriodIds)){
						array_push($updatePeriods,$period);
						$oldPeriodIds = array_diff($oldPeriodIds,array($period->Id));
					}
				}
			}
			if ($oldPeriodIds){
				$deletePeriods = $oldPeriodIds;
			}
			
			if ($newPeriods){
				$this->addAll($newPeriods);
			}
			if ($updatePeriods){
				$this->setModelName('\haibao\cms\model\data\PageControlDataPeriod');
				foreach ($updatePeriods as $updatePeriod){
					$sql = 'update PageControlDataPeriod set StartTime=%s,EndTime=%s where id=%s';
					$this->query($sql,array($updatePeriod->StartTime,$updatePeriod->EndTime,$updatePeriod->Id));
				}
			}
			if ($deletePeriods){
				$sql = 'update PageControlDataPeriod set Status='.\haibao\cms\model\data\PageControlDataPeriod::STATUS_DISABLE.' where Id in ('.implode(',',$deletePeriods).')';
				$this->query($sql);
			}
			
			$this->setModelName('\haibao\cms\model\data\PageControl');
		}
		catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		
		$this->endTranscation();
	}
	
	public function getPeriodsByDataId($dataId){
		$data = array();
		$sql = 'select * from PageControlDataPeriod where ControlDataId='.$dataId;
		$result = $this->query($sql);
		while ($row = $result->fetch_assoc()){
			$model = new \haibao\cms\model\data\PageControlDataPeriod();
			$model->loadArray($row);
			array_push($data,$model);
		}
		
		return $data;
	}
	
	public function addPageControlData($dataModel){
		$this->beginTranscation();
		try{
			$this->add($dataModel);
			$periods = $dataModel->Periods;
			foreach ($periods as $period){
				$period->CreateTime = $dataModel->CreateTime;
				$period->CreateBy = $dataModel->CreateBy;
				$period->Status = \haibao\cms\model\data\PageControlDataPeriod::STATUS_ENABLE;
				$period->ControlDataId = $dataModel->Id;
			}
			$this->addAll($periods);
		}
		catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
		
		$this->endTranscation();
	}
	
	public function getPageContolDataCount($id){
		$num = 0;
		$sql = 'select count(*) as num from PageControlData where id='.$this->escape($id);
		$sql .= ' and Status in ('.\haibao\cms\model\data\PageControlData::STATUS_WAITING.','.\haibao\cms\model\data\PageControlData::STATUS_ON_LINE.')';
		$result = $this->query($sql);
		if ($result->fetch_assoc()){
			$num = $result->getData('num');
		}
		
		return $num;
	}
	
	/**
	 * 获取控件分类
	 * @param \haibao\cms\model\filter\PageControlCategory $filter
	 */
	public function getAllCategory($filter){
		
		
		return $this->getAll($filter);;
	}
	
	/**
	 * @param \haibao\cms\model\data\PageControlCategory $model
	 */
	public function addCategory($model){
		try{
			$this->beginTranscation();
			$this->add($model);
			
			if (!$model->ParentId){
				$sql = 'insert into ControlCategoryMap(CategoryId, ParentId) Values (%s,0),(%s,%s)';
				$this->query($sql,array_pad(array(), 3, $model->Id));
			}
			else{
				$sql = 'insert into ControlCategoryMap(CategoryId, ParentId)
					select CategoryId, ParentId from (
						(select %s as CategoryId, ParentId from ControlCategoryMap where CategoryId = %s and ParentId !=0)
						union
						(select %s,%s from ControlCategoryMap limit 1)
					) a';
				$this->query($sql, array(
					$model->Id, $model->ParentId, $model->Id, $model->Id,
				));
			}
			
			$this->endTranscation();
		}
		catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
	}
	
	/**
	 * 更新控件分类
	 */
	public function updateCategoryById($id,$arrSet){
		try{
			$this->beginTranscation();
			$this->updateById($id, $arrSet);
				
			if (isset($arrSet[\haibao\cms\model\filter\PageControlCategory::CONDITION_FIELD_NAME_PARENT_ID])){
				$parentId = $arrSet[\haibao\cms\model\filter\PageControlCategory::CONDITION_FIELD_NAME_PARENT_ID];
				
				$sql = 'delete from ControlCategoryMap where Id in (
						select Id from
							(
								select map.Id from ControlCategoryMap map inner join (
									select * from
									(
										select a.ParentId from ControlCategoryMap a where a.CategoryId = %s and a.ParentId <> %s
									) a
									join
									(
										select b.CategoryId from ControlCategoryMap b where b.ParentId = %s
									) b
								) tmp ON map.ParentId = tmp.ParentId and map.CategoryId = tmp.CategoryId
							) a
						)';
				$this->query($sql, array_pad(array(), 3, $id));
					
				$sql = 'insert into ControlCategoryMap (CategoryId, ParentId) select b.CategoryId,a.ParentId from
						(
							select ParentId from ControlCategoryMap where CategoryId = %s
						) a join (
							select CategoryId from ControlCategoryMap where ParentId = %s
						) b';
				$this->query($sql, array($parentId, $id));
			}
				
			$this->endTranscation();
		}
		catch (\Exception $e){
			$this->rollback();
			throw $e;
		}
	}
	
	public function getPageControlDataById($id){
	    $parameterValue = '';
	    $sql = "select ParameterValue from PageControlData where Id=%s";
	    $result = $this->query($sql, array($id));
	    if ($result->fetch_assoc()){
	        $parameterValue = $result->getData('ParameterValue');
	    }
	    return $parameterValue;
	}
	
	public function getPageControlDataByControlId($cid){
		$result = array();
		$sql = "select ParameterValue from PageControlData where ControlId=%s";
		$data = $this->query($sql, array($cid));
		while ($data->fetch_assoc()){
			$result[] = json_decode($data->getData('ParameterValue'));
		}
		return $result;
	}
	
	public function getOnLinePageControlDataByControlId($controlId){
	    $result = array();
	    $sql = "select ParameterValue from PageControlData where ControlId=%s and Status = 3";
	    $data = $this->query($sql, array($controlId));
	    while ($data->fetch_assoc()){
	        $result[] = json_decode($data->getData('ParameterValue'));
	    }
	    return $result;
	}
	
	/**
	 * 更新控件手动数据状态
	 * @param : $id
	 * @param : $status
	 */
	public function changeControlDataStatus($id,$status){
		
		$sql = "update PageControlData set Status=%s where Id=%s";
		$this->query($sql,array($status,$id));
	}
	
	public function setControlDataClickNum($id){
		$sql = "update PageControlData set ClickNum=ClickNum+1 where Id=%s";
		$this->query($sql,array($id));
	}
	
	/**
	 * 控件数据重排顺序
	 * @param array $idArr
	 */
	public function reSortOnlineData($idArr){
		$ids = implode(',',$idArr); 
		$sql = "update PageControlData set OrderNo = CASE Id ";
		foreach($idArr as $value=>$id){
			$sql .= sprintf("WHEN %d THEN %d ", $id, $value+1);
		}
		$sql .= "END WHERE Id in ($ids)";
		$this->query($sql);
	}
}